<!--
 * @description 信息脱敏设置
 * @author wancheng
 * @date 2021/10/15
 -->
<template>
  <section class="desensitization">
    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>脱敏设置</span>
        <el-button
          v-show="activeTab==='2'"
          :loading="loading4news"
          style="margin-right:10px; padding:10px 30px;"
          @click="handleNewsAdd"
        >添加
        </el-button>
      </section>
    </section>
    <div class="classify-tab">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane v-for="item in checkList" :key="item.id" :label="item.name" :name="item.id" />
      </el-tabs>
    </div>
    <section class="main-table">
      <!-- 模块脱敏配置 -->
      <section v-if="activeTab==='1'" class="inner-table">
        <el-card class="box-card" style="margin-bottom: 10px;">
          <el-checkbox v-model="showUpdate4Phone" label="1" @change="updateConfig('phone')">会员信息修改时手机号码展示当前值</el-checkbox>
          <el-checkbox v-model="showUpdate4IdNo" label="1" @change="updateConfig('idNo')">会员信息修改时证件号码展示当前值</el-checkbox>
        </el-card>
        <el-table
          :data="tmMaskingList"
          :span-method="arraySpanMethod"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id"
          size="mini"
          :indent="30"
        >
          <el-table-column label="配置名称" min-width="200">
            <template slot-scope="scope">
              <el-input
                v-if="scope.row.code !== 'default'"
                v-model="scope.row.name"
                class="edit-input"
                size="small"
              />
              <section v-else style="text-align: center;">默认脱敏规则</section>
            </template>
          </el-table-column>
          <el-table-column label="配置标识" min-width="150">
            <template slot-scope="scope">
              <el-select v-if="scope.row.code !== 'default'" v-model="scope.row.code" @change="handleCodeBlur(scope.row.code,scope.row)">
                <el-option
                  v-for="(item,index) in options"
                  :key="index"
                  :label="`${item.dictValue}(${item.dictName})`"
                  :value="item.dictValue"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="手机号码" min-width="300">
            <template slot-scope="scope">
              <section class="news-item">
                <el-checkbox-group v-model="scope.row.phoneNum" style="display: inline-block">
                  <el-checkbox label="1">展示时不脱敏</el-checkbox>
                  <el-checkbox label="2">导出时不脱敏</el-checkbox>
                </el-checkbox-group>
              </section>
            </template>
          </el-table-column>
          <el-table-column label="证件号码" min-width="300">
            <template slot-scope="scope">
              <section class="news-item">
                <el-checkbox-group v-model="scope.row.idNo" style="display: inline-block">
                  <el-checkbox label="1">展示时不脱敏</el-checkbox>
                  <el-checkbox label="2">导出时不脱敏</el-checkbox>
                </el-checkbox-group>
              </section>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.code != 'default'"
                type="text"
                style="color:#18A5FD;font-size:14px;"
                @click="handleNewsDelete(scope)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="btnBox">
          <el-button
            :loading="loading4news"
            style="margin-right:10px; padding:10px 30px;"
            @click="handleNewsAdd"
          >添加
          </el-button>
          <el-button
            :loading="loading4news"
            type="primary"
            @click="handleComit()"
          >确 定
          </el-button>
        </div>
      </section>
      <!-- 特殊脱敏配置 -->
      <section v-if="activeTab==='2'" class="inner-table">
        <el-table
          :data="tsMaskingList"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id"
          size="mini"
          :indent="30"
        >
          <el-table-column label="配置名称" min-width="250">
            <template slot-scope="scope">
              {{ scope.row.infoName }}
            </template>
          </el-table-column>
          <el-table-column label="配置标识" min-width="250">
            <template slot-scope="scope">
              <span>{{ scope.row.infoFlag }}</span>
            </template>
          </el-table-column>
          <el-table-column label="配置ID" min-width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.infoId }}</span>
            </template>
          </el-table-column>
          <el-table-column label="手机号码" min-width="300">
            <template slot-scope="scope">
              <section class="news-item">
                <el-checkbox-group v-model="scope.row.infoConfig.phoneNum" style="display:inline-block">
                  <el-checkbox :label="1" style="margin-right:10px;" disabled>展示时不脱敏</el-checkbox>
                  <el-checkbox :label="2" style="margin-right:10px;" disabled>导出时不脱敏</el-checkbox>
                </el-checkbox-group>
              </section>
            </template>
          </el-table-column>
          <el-table-column label="证件号码" min-width="300">
            <template slot-scope="scope">
              <section class="news-item">
                <el-checkbox-group v-model="scope.row.infoConfig.idNo" style="display: inline-block">
                  <el-checkbox :label="1" style="margin-right:10px;" disabled>展示时不脱敏</el-checkbox>
                  <el-checkbox :label="2" disabled>导出时不脱敏</el-checkbox>
                </el-checkbox-group>
              </section>
            </template>
          </el-table-column>
          <el-table-column label="排序" width="100">
            <template slot-scope="scope">
              {{ scope.row.sort }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.code != 'default'"
                type="text"
                style="color:#18A5FD;font-size:14px;"
                @click="handleStatus(scope)"
              >{{ scope.row.status==='ZT01'?'禁用':'启用' }}
              </el-button>
              <el-button
                type="text"
                style="color:#18A5FD;font-size:14px;"
                @click="handleEdit(scope)"
              >编辑
              </el-button>
              <el-button
                v-if="scope.row.code != 'default'"
                type="text"
                style="color:#18A5FD;font-size:14px;"
                @click="handleNewsDelete(scope)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          @pagination="getList"
        />
      </section>

    </section>
    <!--模块配置添加  -->
    <el-dialog title="添加配置" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="配置名称" prop="name" label-width="150">
          <el-input v-model="form.name" autocomplete="off" style="width:80%" />
        </el-form-item>
        <el-form-item label="配置标识" prop="code" label-width="150">
          <!-- <el-input v-model="form.code" autocomplete="off" style="width:80%" /> -->
          <el-select v-model="form.code" style="width:80%" @change="handleCodeBlur(form.code,form)">
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="`${item.dictValue}(${item.dictName})`"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号">
          <el-checkbox-group v-model="form.phoneNum" style="display: inline-block">
            <el-checkbox :label="1">展示时不脱敏</el-checkbox>
            <el-checkbox :label="2">导出时不脱敏</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="证件号">
          <el-checkbox-group v-model="form.idNo" style="display: inline-block">
            <el-checkbox :label="1">展示时不脱敏</el-checkbox>
            <el-checkbox :label="2">导出时不脱敏</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSumbit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 特殊配置添加 -->
    <el-dialog title="添加配置" :visible.sync="dialogFormVisibletwo">
      <el-form ref="form2" :model="form2" :rules="rules">
        <el-form-item label="配置名称" prop="infoName" label-width="150">
          <el-input v-model="form2.infoName" autocomplete="off" style="width:80%" />
        </el-form-item>
        <el-form-item label="配置标识" prop="infoFlag" label-width="150">
          <!-- <el-input v-model="form2.infoFlag" autocomplete="off" style="width:80%" /> -->
          <el-select v-model="form2.infoFlag" style="width:80%" @change="changeName(form2.infoFlag,form2)">
            <el-option
              v-for="(item,index) in options"
              :key="index"
              :label="`${item.dictValue}(${item.dictName})`"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配置ID" prop="infoId" label-width="150">
          <el-input v-model="form2.infoId" autocomplete="off" style="width:80%" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-checkbox-group v-model="form2.infoConfig.phoneNum" style="display: inline-block">
            <el-checkbox :label="1">展示时不脱敏</el-checkbox>
            <el-checkbox :label="2">导出时不脱敏</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="证件号">
          <el-checkbox-group v-model="form2.infoConfig.idNo" style="display: inline-block">
            <el-checkbox :label="1">展示时不脱敏</el-checkbox>
            <el-checkbox :label="2">导出时不脱敏</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="排序" abel-width="150">
          <el-input v-model="form2.sort" autocomplete="off" style="width:80%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisibletwo = false">取 消</el-button>
        <el-button type="primary" @click="handleSumbit">确 定</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import Pagination from '@/components/Pagination'
import { sysDesensitizationConfigQueryPage, getDataByType, sysDesensitizationConfigInseter, sysDesensitizationConfiguUpdateStatus, getConfig, save, sysDesensitizationConfigUpdate, sysDesensitizationConfigDelete, getDic } from '../api'
import permission from '@/directive/permission'
import { deepClone } from '@/utils/index.js'
export default {
  name: 'Desensitization',
  components: { Pagination },
  directives: { permission },
  data() {
    return {
      searchshow: true,
      listQuery: {
        page: 1,
        limit: 10
      },
      activeTab: '1',
      checkList: [
        {
          name: '模块脱敏配置',
          id: '1'
        },
        {
          name: '特殊脱敏配置',
          id: '2'
        }
      ],
      tmMaskingList: [],
      tsMaskingList: [],
      total: 0,
      listLoading: false,
      tab: '1',
      loading4news: false,
      dialogFormVisible: false,
      form: {
        name: '', // 名称
        code: '', // 标识
        phoneNum: [], // 1代表显示不脱敏  2代表导出不脱敏
        idNo: [] // 同上
      },
      form2: {
        infoName: '',
        infoFlag: '',
        infoId: '',
        infoConfig: {
          phoneNum: [],
          idNo: []
        },
        status: '',
        sort: ''
      },
      dialogFormVisibletwo: false,
      configInfo: {},
      rules: {
        name: [
          { required: true, message: '请输入配置名称', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入配置标识', trigger: 'blur' }
        ],
        infoName: [
          { required: true, message: '请输入配置名称', trigger: 'blur' }
        ],
        infoFlag: [
          { required: true, message: '请输入配置标题', trigger: 'blur' }
        ],
        infoId: [
          { required: true, message: '请输入配置id', trigger: 'blur' }
        ]

      },
      handleType: 'create',
      options: [],
      list: [],
      showUpdate4Phone: false,
      showUpdate4IdNo: false
    }
  },
  created() {
    this.init()
    getDic({
      dictCode: 'CDMKMC'
    }).then(res => {
      this.options = res.data.data[0].list
    })
  },
  methods: {
    getConfig(type) {
      return new Promise((resolve, reject) => {
        getConfig({ name: type }).then(res => {
          resolve(res.data.data.configValue === '1')
        }).catch(() => {
          reject('')
        })
      })
    },
    updateConfig(t) {
      const configName = t === 'phone' ? 'SYS_USER_IS_SHOW_PHON_NUMBER' : 'SYS_USER_IS_SHOW_ID_NUMBER'
      const configValue = t === 'phone' ? (this.showUpdate4Phone ? '1' : '0') : (this.showUpdate4IdNo ? '1' : '0')
      return new Promise((resolve, reject) => {
        save({ configName: configName, configValue: configValue }).then(res => {

        }).catch(() => {
          reject('')
        })
      })
    },
    handleBack() {
      this.$router.back()
    },
    /**
     * 选项卡切换
     */
    handleTabClick({ name }) {
      this.activeTab = name
      if (name === '2') {
        this.listQuery.page = 1
        this.getList()
      } else {
        this.init()
      }
    },
    getList() {
      this.listLoading = true
      const query = {
        page: this.listQuery.page,
        pageSize: this.listQuery.limit
      }
      return new Promise((resolve, reject) => {
        sysDesensitizationConfigQueryPage(query).then(res => {
          this.tsMaskingList = res.data.data.rows && res.data.data.rows.map(
            (item) => {
              return {
                ...item,
                infoConfig: item.infoConfig && JSON.parse(item.infoConfig)
              }
            }
          )
          this.total = res.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },
    async init() {
      this.showUpdate4Phone = await this.getConfig('SYS_USER_IS_SHOW_PHON_NUMBER')
      this.showUpdate4IdNo = await this.getConfig('SYS_USER_IS_SHOW_ID_NUMBER')
      getDataByType({ name: 'KEY_INFO_DESENSITIZATION' }).then(
        (res) => {
          if (res.data.code === '200') {
            const list = res.data.data.configValue ? JSON.parse(res.data.data.configValue) : []
            const defalut = res.data.data.configValue && JSON.parse(res.data.data.configValue).default
            this.tmMaskingList = Array.isArray(list.special) ? list.special.unshift(defalut) && list.special : [defalut]
            this.deepList()
          }
        }
      )
    },
    // 表格合并
    arraySpanMethod({
      row,
      column,
      rowIndex,
      columnIndex
    }) {
      if (rowIndex === 0) {
        if (columnIndex === 0) {
          return [1, 2]
        } else if (columnIndex === 1) {
          return [0, 0]
        }
      }
    },
    // 添加配置
    handleNewsAdd() {
      if (this.activeTab === '1') {
        this.tmMaskingList.push({
          name: '', // 名称
          code: '', // 标识
          phoneNum: [], // 1代表显示不脱敏  2代表导出不脱敏
          idNo: [] // 同上
        })
      } else {
        this.dialogFormVisibletwo = true
        this.form2 = {
          infoName: '',
          infoFlag: '',
          infoId: '',
          infoConfig: {
            phoneNum: [],
            idNo: []
          },
          status: '',
          sort: '' }
      }
      this.handleType = 'create'
    },
    // 查询修改的字段是否已存在
    handleCodeBlur(v, scoped) {
      if (v) {
        const t = this.list.find(a => (a.code === v))
        if (t) {
          return this.$message({
            message: '模块代码已存在',
            type: 'warning',
            duration: 2000
          })
        }
        if (scoped) {
          this.options.forEach(item => {
            if (item.dictValue === v) {
              scoped.name = item.dictName
              if (scoped.$index) {
                this.$set(this.tmMaskingList[scoped.$index], 'name', item.dictName)
              } else {
                this.$set(scoped, 'name', item.dictName)
              }
            }
          })
        }
        this.deepList()
      }
    },
    changeName(v, scoped) {
      if (scoped) {
        this.options.forEach(item => {
          if (item.dictValue === v) {
            this.$set(scoped, 'infoName', item.dictName)
          }
        })
      }
    },
    deepList(params = 'tmMaskingList') {
      this.list = deepClone(this[params])
    },
    // 处理添加的确认按钮
    handleSumbit() {
      if (this.activeTab === '1') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.handleType === 'create') {
              this.tmMaskingList.push(this.form)
            } else if (this.handleType === 'edit') {
              this.$set(this.tmMaskingList, this.form.$index, this.form)
            }
            this.init()
          } else {
            return false
          }
        })
      } else {
        this.$refs['form2'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            if (this.handleType === 'create') {
              // 调用新建接口
              const params = {
                ...this.form2,
                infoConfig: this.form2.infoConfig ? JSON.stringify(this.form2.infoConfig) : '{"phoneNum":"[]","idNo":"[]"}'
              }
              sysDesensitizationConfigInseter(params).then(
                res => {
                  loading.close()
                  this.$message({
                    type: 'success',
                    message: '操作成功'
                  })
                  this.getList()
                }
              ).catch(err => {
                loading.close()
              })
            } else if (this.handleType === 'edit') {
              // 调用修改接口
              console.log(this.form2)
              const params = {
                ...this.form2,
                infoConfig: this.form2.infoConfig ? JSON.stringify(this.form2.infoConfig) : '{"phoneNum":"[]","idNo":"[]"}'
              }
              sysDesensitizationConfigUpdate(params).then(res => {
                loading.close()
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
                this.getList()
              }).catch(err => {
                loading.close()
              })
            }
          } else {
            return false
          }
        })
      }
      this.dialogFormVisible = false
      this.dialogFormVisibletwo = false
    },
    // 处理是否禁用
    handleStatus(scope) {
      const code = scope.row.status === 'ZT01' ? 'ZT02' : 'ZT01'
      sysDesensitizationConfiguUpdateStatus({
        status: code,
        id: scope.row.id

      }).then(res => {
        this.$message({
          type: 'success',
          message: '操作成功'
        })
        this.getList()
      })
    },
    // 处理编辑
    handleEdit(scope) {
      if (this.activeTab === '1') {
        this.dialogFormVisible = true
        this.form = deepClone(scope.row)
      } else {
        this.dialogFormVisibletwo = true
        this.form2 = deepClone(scope.row)
      }
      this.handleType = 'edit'
    },
    // 处理删除
    handleNewsDelete(scope) {
      if (this.activeTab === '1') {
        this.$confirm('此操作将永久删除该配置, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tmMaskingList.splice(scope.$index, 1)
          this.$message({
            message: '已删除',
            type: 'success',
            duration: 2000
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      } else {
        this.$confirm('此操作将永久删除该配置, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 调用接口
          sysDesensitizationConfigDelete({ id: scope.row.id }).then(res => {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    // 配置提交
    handleComit() {
      const flag = this.isOnly(this.tmMaskingList)
      if (flag) {
        return this.$message({
          type: 'warning',
          message: '选择的配置标识有重复'
        })
      }
      const obj = {}
      const copyArr = [...this.tmMaskingList]
      obj.default = copyArr.shift()
      obj.special = copyArr
      if (copyArr.some(item => {
        return item.name.trim() === ''
      })) {
        return this.$message({
          type: 'warning',
          message: '请填写配置名称'
        })
      }
      if (copyArr.some(item => {
        return item.code.trim() === ''
      })) {
        return this.$message({
          type: 'warning',
          message: '请选择配置标识'
        })
      }

      const parmas = {
        configName: 'KEY_INFO_DESENSITIZATION',
        configValue: JSON.stringify(obj)
      }
      save(parmas).then(res => {
        this.$message({
          message: res.data.data,
          type: 'success'
        })
        this.init()
      })
    },
    isOnly(list = []) {
      return list.some(item => {
        return list.filter(i => { return item.code === i.code }).length > 1
      })
    }

  }
}
</script>
<style lang="scss">

.desensitization {
  padding: 10px;

  .main-search {
    background-color: #fff;
    padding: 0 10px;

    .svg-container {
      padding: 0 5px 0 10px;
      color: #bfced6;
      vertical-align: middle;
      display: inline-block;
    }

    .search-input {
      width: 60%;
      position: relative;

      &:after {
        content: '';
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }

      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;

        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }

    .search-btn {
      display: inline-block;
      float: right;

      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }

      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }

    &.separate {
      .search-inner {
        padding-top: 10px;

        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }

          .el-input {
            position: relative;

            &.el-date-editor input {
              padding-left: 30px;
            }

            .el-input__inner {
              border: none;
              padding: 0;
            }

            &:after {
              content: '';
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }

      .search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }

  .classify-tab {
    width: 100%;
    margin-bottom: 10px;
    padding: 0 10px;
    background-color: #fff;
    display: flex;
    border-radius: 4px;

    .el-tabs__nav-wrap::after {
      display: none;
    }

    .el-tabs__header {
      margin: 0;
    }
  }

  .main-buttons {
    display: flex;
    line-height: 36px;
    margin-top: 10px;

    .main-buttons-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);
      display: flex;
      justify-content: space-between;
    }
  }
  .news-add {
      cursor: pointer;
      // width: 100%;
      line-height: 40px;
      text-align: center;
      border: 1px dotted #e5e5e5;

      &:hover {
        @include border-color(1px, dotted, $mainColor);
        @include font-color($mainColor);
      }
    }
  .btnBox{
      text-align: center;
    }
   th{
      .cell{
        text-align: center;
      }
    }
  .cell{
    text-align: center;
  }
  .el-checkbox__input.is-disabled.is-checked{
    .el-checkbox__inner{
     background-color: $mainColor;
     border-color: $mainColor;

     &::after{
       content: '';
       border-color:white;
     }
    }
  }
  .el-checkbox__input.is-disabled.is-checked+span.el-checkbox__label {
    color: $mainColor;
    cursor: not-allowed;
  }
}
</style>
